package problema024;

public class LexicographicPermutations {
	
	public static void main(String[] args){
		dameLa1000000();
	}
	
	public static void dameLa1000000(){
		int[] numeros = {0,1,2,3,4,5,6,7,8,9};
		for(int i = 1; i < 1000000; i++){
			if(!nextPermutation(numeros)) System.out.println("ERROR");
		}
		imprimir(numeros);
	}
	
	public static void imprimir(int[] n){
		for(int i = 0; i < n.length; i++){
			System.out.print(n[i] + " ");
		}
		System.out.println();
	}
	
	public static boolean nextPermutation(int[] p) {          
        //Step 1
        int a = p.length - 2;          
        while (a >= 0 && p[a] >= p[a + 1]) {              
            a--;          
        }          
        if (a == -1) {              
            return false;          
        }
        
        //Step 2
        int b = p.length - 1;          
        while (p[b] <= p[a]) {              
            b--;          
        }
        
        //Step 3
        int t = p[a];          
        p[a] = p[b];          
        p[b] = t;          
        
        //Step 4
        for (int i = a + 1, j = p.length - 1; i < j; i++, j--) {              
            t = p[i];              
            p[i] = p[j];
            p[j] = t;
        }
        return true;
    }

}
